---
import Footer from '@layouts/Footer.astro';
import { getChangeLogs } from '@utils/collections/changelogs';
import {
  RectangleGroupIcon,
  ServerIcon,
  BoltIcon,
  ChatBubbleLeftIcon,
  MagnifyingGlassIcon,
  QueueListIcon,
} from '@heroicons/react/24/outline';
import { DatabaseIcon } from 'lucide-react';
import { render, getEntry } from 'astro:content';
import mdxComponents from '@components/MDX/components';
import 'diff2html/bundles/css/diff2html.min.css';

import { buildUrl } from '@utils/url-builder';
import { getPreviousVersion } from '@utils/collections/util';
import { getDiffsForCurrentAndPreviousVersion } from '@utils/collections/file-diffs';
import VerticalSideBarLayout from '@layouts/VerticalSideBarLayout.astro';
import { ClientRouter } from 'astro:transitions';
import { isChangelogEnabled } from '@utils/feature';

import { Page } from './_index.data';

export const prerender = Page.prerender;
export const getStaticPaths = Page.getStaticPaths;

// Get data
const props = await Page.getData(Astro);

if (!isChangelogEnabled()) {
  return Astro.redirect('/docs');
}

let collectionItem = props;
const logs = await getChangeLogs(props);

const { data } = props;
const latestVersion = data.latestVersion;

const renderedLogs = logs.map(async (log) => {
  const logEntry = await getEntry('changelogs', log.id);
  const { Content } = await render(logEntry as any);
  return {
    Content,
    ...log,
  };
});

const logsToRender = await Promise.all(renderedLogs);

const logListPromise = logsToRender.map(async (log, index) => {
  const currentLogVersion = log.data.version;
  const previousLogVersion = log.data.version ? getPreviousVersion(log.data.version, data.versions || []) : '';
  return {
    id: log.id,
    url: buildUrl(`/docs/${props.collection}/${props.data.id}`),
    isLatest: log.data.version === latestVersion,
    version: log.data.version,
    createdAt: log.data.createdAt,
    badges: log.data.badges || [],
    Content: log.Content,
    diffs:
      currentLogVersion && previousLogVersion
        ? await getDiffsForCurrentAndPreviousVersion(
            currentLogVersion,
            previousLogVersion,
            collectionItem.data.id,
            props.allCollectionItems
          )
        : [],
  };
});

const logList = await Promise.all(logListPromise);

const getBadge = () => {
  if (props.collection === 'services') {
    return { backgroundColor: 'pink', textColor: 'pink', content: 'Service', icon: ServerIcon, class: 'text-pink-400' };
  }
  if (props.collection === 'events') {
    return { backgroundColor: 'orange', textColor: 'orange', content: 'Event', icon: BoltIcon, class: 'text-orange-400' };
  }
  if (props.collection === 'commands') {
    return { backgroundColor: 'blue', textColor: 'blue', content: 'Command', icon: ChatBubbleLeftIcon, class: 'text-blue-400' };
  }
  if (props.collection === 'queries') {
    return { backgroundColor: 'green', textColor: 'green', content: 'Query', icon: MagnifyingGlassIcon, class: 'text-blue-400' };
  }
  if (props.collection === 'domains') {
    return {
      backgroundColor: 'yellow',
      textColor: 'yellow',
      content: 'Domain',
      icon: RectangleGroupIcon,
      class: 'text-yellow-400',
    };
  }
  if (props.collection === 'containers') {
    return { backgroundColor: 'blue', textColor: 'blue', content: 'Container', icon: DatabaseIcon, class: 'text-blue-400' };
  }
  if (props.collection === 'flows') {
    return { backgroundColor: 'teal', textColor: 'teal', content: 'Flow', icon: QueueListIcon, class: 'text-teal-400' };
  }
};

const badges = [getBadge()];
---

<VerticalSideBarLayout title="ChangeLog">
  <main class="w-full md:pt-4 px-8 overflow-y-auto h-full max-w-[95%]">
    <nav aria-label="Breadcrumb" class="flex">
      <ol role="list" class="flex items-center space-x-2">
        <li>
          <div>
            <a
              href={buildUrl(`/docs/${props.collection}/${props.data.id}/${props.data.version}`)}
              class="text-sm font-medium text-gray-500 hover:text-gray-700"
            >
              {props.data.name}
            </a>
          </div>
        </li>
        <li>
          <div class="flex items-center">
            <svg fill="currentColor" viewBox="0 0 20 20" aria-hidden="true" class="h-5 w-5 flex-shrink-0 text-gray-300">
              <path d="M5.555 17.776l8-16 .894.448-8 16-.894-.448z"></path>
            </svg>
            <a
              href={buildUrl(`/docs/${props.collection}/${props.data.id}/${props.data.version}`)}
              class="text-sm font-medium text-gray-500 hover:text-gray-700"
            >
              Changelog
            </a>
          </div>
        </li>
      </ol>
    </nav>
    <div class="border-b border-gray-200 flex justify-between items-start py-4 w-full">
      <div>
        <h2 class="text-2xl md:text-4xl font-bold">{props.data.name} (Changelog)</h2>
        <h2 class="text-lg pt-2 text-gray-500 font-light">{props.data.summary}</h2>
        {
          badges && (
            <div class="flex flex-wrap py-2 pt-4">
              {badges.map((badge: any) => (
                <span
                  class={`text-sm font-light text-gray-500 px-2 py-1 rounded-md mr-2 bg-${badge.backgroundColor}-100 space-x-1 border border-${badge.backgroundColor}-200 text-${badge.textColor}-800 flex items-center ${badge.class ? badge.class : ''} `}
                >
                  {badge.icon && <badge.icon className="w-4 h-4 inline-block mr-1 " />}
                  <span>{badge.content}</span>
                </span>
              ))}
            </div>
          )
        }
      </div>
    </div>
    {
      logList.length === 0 && (
        <div class="py-4 text-gray-400 prose prose-md">
          <p>No changelogs found.</p>
        </div>
      )
    }
    <div class="flow-root py-8 w-full">
      <ul role="list" class="-mb-8">
        {
          logList.map((log, index) => (
            <li>
              <div class="relative pb-8">
                {index !== logList.length - 1 ? (
                  <span aria-hidden="true" class="absolute left-6 top-4 -ml-px h-full w-0.5 bg-gray-200" />
                ) : null}
                <div class="relative flex space-x-3">
                  <div>
                    <a
                      href={buildUrl(`${log.url}/${log.version}`)}
                      class={
                        'bg-primary hover:bg-primary/80 text-white flex h-8 w-14 items-center justify-center rounded-full ring-8 ring-white'
                      }
                    >
                      {log.version}
                      {/* <DocumentTextIcon aria-hidden="true" className="h-5 w-5 text-white" /> */}
                    </a>
                  </div>
                </div>
                <div class="pl-[70px] py-2 -mt-10">
                  {log.createdAt && (
                    <div class="pb-2">
                      <h3 class="text-2xl text-gray-800 font-bold">
                        <span>
                          {log.createdAt.toISOString().split('T')[0]} {`${log.isLatest ? '(latest)' : ''}`}
                        </span>
                      </h3>
                    </div>
                  )}
                  {log.badges && (
                    <div class="flex flex-wrap">
                      {log.badges.map((badge: any) => (
                        <span
                          class={`text-sm font-light text-gray-500 px-2 py-1 rounded-md mr-2 bg-${badge.backgroundColor}-100 space-x-1 border border-${badge.backgroundColor}-200 text-${badge.textColor}-800 flex items-center ${badge.class ? badge.class : ''} `}
                        >
                          {badge.icon && <badge.icon className="w-4 h-4 inline-block mr-1 " />}
                          <span>{badge.content}</span>
                        </span>
                      ))}
                    </div>
                  )}
                  <div class="prose prose-md !max-w-none py-2">
                    <log.Content components={mdxComponents(props)} />
                  </div>
                  {log.diffs && log.diffs.map((diff) => <div id="diff-container" set:html={diff} />)}
                </div>
              </div>
            </li>
          ))
        }
      </ul>
    </div>
    <Footer />
  </main>
  <ClientRouter />
</VerticalSideBarLayout>
